package com.lovezy.platform.core.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.function.Function;

/**
 * Mybatis 帮助类
 * Created by jin on 2017/11/4.
 */
public final class MapperHelper {

    private SqlSessionFactory factory;

    public MapperHelper(SqlSessionFactory factory) {
        this.factory = factory;
    }

    public <T, MAPPER> T callMapper(Class<MAPPER> m, Function<MAPPER, T> action) {
        return doSql(session -> {
            MAPPER mapper = session.getMapper(m);
            return action.apply(mapper);
        });
    }

    public <T> T doSql(Function<SqlSession, T> action) {
        SqlSession sqlSession = buildSession();
        T t = action.apply(sqlSession);
        sqlSession.close();
        return t;
    }

    private SqlSession buildSession() {
        return factory.openSession();
    }
}
